﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogicLayer.Manager;
using Objects;
using AutoFix.ClientComponents;
using AutoFix.Base;
using AutoFix.controls;
using Common;
using System.IO;

namespace AutoFix
{
    public partial class add_step : BasePage
    {
        #region [Private Members]
        /// <summary>
        /// Holds the article
        /// </summary>
        private Article article = null;
        #endregion

        #region [Base Implementations]
        /// <summary>
        /// Gets or sets a value indicating whether [is login page].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [is login page]; otherwise, <c>false</c>.
        /// </value>
        protected override bool IsLoginPage
        {
            get { return false; }
        }

        /// <summary>
        /// Gets or sets a value indicating whether [is anonymous page].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [is anonymous page]; otherwise, <c>false</c>.
        /// </value>
        protected override bool IsAnonymousPage
        {
            get {return false; }
        }

        /// <summary>
        /// Page name
        /// </summary>
        protected override string PageName
        {
            get { return "Add Step"; }
        }

        /// <summary>
        /// Gets the authorized user types.
        /// </summary>
        protected override List<UserType> AuthorizedUserTypes
        {
            get { return new List<UserType>(new UserType[] { UserType.Admin, UserType.Contributor }); }
        }
      
        #endregion

        #region [Event Handlers]
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {

            article = this.PageSession.Article;
            if (!(Page.IsPostBack))
            {
                switch (article.ArticleTypeID)
                {
                    case (int)ArticleEnums.Blog:
                        this.txtContent.Visible = true;
                        this.rqdStepContent.Visible = true;
                        break;
                    case (int)ArticleEnums.Video:
                        this.lblStepContentTitle.Visible = true;
                        this.fleUploadVideo.Visible = true;
                        this.lblStepContentTitle.Text = "Browse Video:";
                        this.lblFormatMessage.Visible = true;
                        this.rqdVideoFile.Visible = true;
                        break;
                    default:
                        break;
                }
            }

        }
        /// <summary>
        /// Handles the click event of the save step button.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSaveStep_Click(object sender, EventArgs e)
        {
            StepManager stepManager = new StepManager();
            Step step = new Step();
            string fileName = string.Empty;
            string file = string.Empty;
            try
            {
                step.StepName = this.txtStepName.Text;
                step.ArticleID = article.ArticleID;
                step.IsActive = true;
                if ((int)ArticleEnums.Video == article.ArticleTypeID)
                {
                    if (this.fleUploadVideo.HasFile)
                    {
                        if (this.fleUploadVideo.PostedFile.ContentType == "video/mp4")
                        {
                            Guid guid = Guid.NewGuid();
                            string pathToFile = AppConfiguration.ArticlePath + article.ArticleID + "/";
                            string fileToStore = guid + ".mp4";

                            string completeDirectoryPath = Server.MapPath(pathToFile);
                            if (!Directory.Exists(pathToFile))
                            {
                                Directory.CreateDirectory(completeDirectoryPath);
                                completeDirectoryPath = Path.Combine(completeDirectoryPath, fileToStore);
                                if (!File.Exists(completeDirectoryPath))
                                {
                                    file = completeDirectoryPath;
                                    step.StepURL = fileToStore;
                                    this.fleUploadVideo.SaveAs(file);
                                }
                            }
                        }
                        else
                        {
                            this.pageActionMessage.InnerText = "Invalid video file. Only video/mp4 is allowed";
                            this.pageActionMessage.Attributes.Add("class", "error-msg");
                            return;
                        }
                    }
                    else
                    {

                        step.StepURL = "";
                    }
                }

                if ((int)ArticleEnums.Blog == article.ArticleTypeID)
                {
                    Guid guid = Guid.NewGuid();
                    string pathToFile = AppConfiguration.ArticlePath + article.ArticleID + "/";
                    string fileToStore = guid + ".txt";

                    string completeDirectoryPath = Server.MapPath(pathToFile);
                    if (!Directory.Exists(pathToFile))
                    {
                        Directory.CreateDirectory(completeDirectoryPath);
                        completeDirectoryPath = Path.Combine(completeDirectoryPath, fileToStore);
                        if (!File.Exists(completeDirectoryPath))
                        {
                            file = completeDirectoryPath;
                            step.StepURL = fileToStore;
                            this.fleUploadVideo.SaveAs(file);
                            using (FileStream fileStream = File.Create(completeDirectoryPath))
                            {
                                fileStream.Close();
                            }
                            using (StreamWriter stepContentWriter = new StreamWriter(completeDirectoryPath, true))
                            {
                                stepContentWriter.WriteLine(this.txtContent.Text);
                            }

                        }
                    }
                }
                bool success = stepManager.UpdateStep(step);
                if (success)
                {

                    this.pageActionMessage.InnerText = "The step was added successfully to the article. Add another step.";
                    this.pageActionMessage.Attributes.Add("class", "success-msg");
                }
                else
                {

                    this.pageActionMessage.InnerText = "Failed to add a step to the article.";
                    this.pageActionMessage.Attributes.Add("class", "error-msg");
                }

            }
            catch (Exception)
            {
                this.pageActionMessage.InnerText = "Failed to add a step to the article.";
                this.pageActionMessage.Attributes.Add("class", "error-msg");
            }
            finally
            {
                stepManager = null;
                step = null;
                this.txtContent.Text = "";
                this.txtStepName.Text = "";
            }
        }
        /// <summary>
        /// Handles the click event of the publish article button.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnPublishArticle_Click(object sender, EventArgs e)
        {
            ArticleManager articleManager = new ArticleManager();
            List<Article> articles = null;
            Article article = null;
            try
            {
                articles = articleManager.GetArticles(this.article.ArticleID);
                if (articles.Count > 0 && articles != null)
                {
                    if (articles[0].IsActive != false)
                    {
                        article = new Article();
                        article.ArticleID = articles[0].ArticleID;
                        article.ArticleName = articles[0].ArticleName;
                        article.ArticleImageUrl = articles[0].ArticleImageUrl;
                        article.ArticleTypeID = articles[0].ArticleTypeID;
                        article.VehicleModelID = articles[0].VehicleModelID;
                        article.UserID = articles[0].UserID;
                        article.VehicleModelTypeID = articles[0].VehicleModelTypeID;
                        article.VehicleModelTypeYearID = articles[0].VehicleModelTypeYearID;
                        article.IsPublished = true;
                        article.LastUpdatedDate = DateTime.Now.AddTicks(-(DateTime.Now.Ticks % TimeSpan.TicksPerSecond));
                        article.IsActive = true;
                        bool success = articleManager.UpdateArticle(article);
                        if (success)
                        {
                            this.pageActionMessage.InnerText = "The article was published successfully.";
                            this.pageActionMessage.Attributes.Add("class", "success-msg");
                        }
                        else
                        {
                            this.pageActionMessage.InnerText = "Failed to publish article to the system.";
                            this.pageActionMessage.Attributes.Add("class", "error-msg");
                        }
                    }
                    else
                    {
                        this.pageActionMessage.InnerText = "This article cannot be published since it is deleted";
                        this.pageActionMessage.Attributes.Add("class", "error-msg");
                    }
                }
                else
                {
                    this.pageActionMessage.InnerText = "Failed to load articles to publish the article.";
                    this.pageActionMessage.Attributes.Add("class", "error-msg");
                }
            }
            catch (Exception)
            {
                this.pageActionMessage.InnerText = "Failed to load articles to publish the article.";
                this.pageActionMessage.Attributes.Add("class", "error-msg");
            }
            finally
            {
                article =null;
                articles = null;
                articleManager = null;
            }

        }
        #endregion

      

    }
}